package frontend.pages.admin.employee;

import backend.model.admin.CommuterData;
import backend.service.admin.CommuterDataService;
import frontend.core.TimeTrackingWebApplication;
import frontend.model.admin.CommuterDataUIModel;
import frontend.model.admin.EmployeeUIModel;
import frontend.pages.admin.base.AdminPanel;
import frontend.components.other.UserInputCallableAction;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import java.util.ArrayList;
import java.util.List;

public class EmployeePanel extends AdminPanel<EmployeeUIModel> {

    private EmployeeUIModel model;
    private Form commuterDataListForm;

	public EmployeePanel(String id, PageParameters pageParameters, EmployeeUIModel employeeUIModel) {
		super(id, pageParameters);
        this.model = employeeUIModel;
        setOutputMarkupId(true);

		Form<EmployeeUIModel> employeeForm = new EmployeeForm("employeeForm", employeeUIModel);
		add(employeeForm);

        buildCommuterDataListContainer();

        buildAddCommuterDataForm(employeeUIModel);

	}

    private void buildAddCommuterDataForm(EmployeeUIModel employeeUIModel) {
        Form commuterDataForm = new CommuterDataForm("commuterDataForm", new CommuterDataUIModel(employeeUIModel.getDBModel()), getRefreshPageAction());
        if (employeeUIModel.getDBModel().getId() == 0) {
            commuterDataForm.setVisible(false);
        }
        add(commuterDataForm);
    }

    private void buildCommuterDataListContainer() {

        List<CommuterData> commuterDataList = new ArrayList<>();
        if (model.getDBModel().getId() != 0) {
            commuterDataList = loadCommuterDataList();
        }
        commuterDataListForm = new CommuterDataListForm("commuterDataListForm", commuterDataList, getRefreshPageAction());
        commuterDataListForm.setOutputMarkupId(true);
        if (model.getDBModel().getId() == 0 || commuterDataList.size() == 0) {
            commuterDataListForm.setVisible(false);
        }
        add(commuterDataListForm);
    }

    private List<CommuterData> loadCommuterDataList() {
        CommuterDataService commuterDataService = TimeTrackingWebApplication.getService(CommuterDataService.class);
        return commuterDataService.getAllCommuterDataForEmployee(model.getDBModel().getId());
    }

    private UserInputCallableAction getRefreshPageAction() {
        return new UserInputCallableAction() {
            @Override
            public void call(AjaxRequestTarget target, Object userInput) {
                remove(commuterDataListForm);
                buildCommuterDataListContainer();
                target.add(EmployeePanel.this);
            }
        };
    }
}
